import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zyj
 * @date 2022年06月09日 16:27
 */
public class 打印顺序是ABCABC2 {
    public static void main(String[] args) {
        A a = new A();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                a.a();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                a.b();
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                a.c();
            }
        }, "C").start();
    }
}

class A {
    private ReentrantLock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();
    private int number = 1;//1就是A执行,2就是B执行,3是C执行
    public void a() {
        try {
            lock.lock();
            while (number != 1){
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName());
            number = 2;
            condition2.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public void b() {
        try {
            lock.lock();
            while (number != 2){
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName());
            number = 3;
            condition3.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void c() {
        try {
            lock.lock();
            while (number != 3) {
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName());
            number = 1;
            condition1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}